/*
 * http://www.javapractices.com/Topic80.cjp
 */

public final class ReplaceSubstring {

  /**
  * If Java 1.4 is unavailable, the following technique may be used.
  *
  * @param aInput is the original String which may contain substring aOldPattern
  * @param aOldPattern is the non-empty substring which is to be replaced
  * @param aNewPattern is the replacement for aOldPattern
  */
  public static String oldReplace(
    final String aInput,
    final String aOldPattern,
    final String aNewPattern
  ){
     if ( aOldPattern.equals("") ) {
        throw new IllegalArgumentException("Old pattern must have content.");
     }

     final StringBuffer result = new StringBuffer();
     //startIdx and idxOld delimit various chunks of aInput; these
     //chunks always end where aOldPattern begins
     int startIdx = 0;
     int idxOld = 0;
     while ((idxOld = aInput.indexOf(aOldPattern, startIdx)) >= 0) {
       //grab a part of aInput which does not include aOldPattern
       result.append( aInput.substring(startIdx, idxOld) );
       //add aNewPattern to take place of aOldPattern
       result.append( aNewPattern );

       //reset the startIdx to just after the current match, to see
       //if there are any further matches
       startIdx = idxOld + aOldPattern.length();
     }
     //the final chunk will go to the end of aInput
     result.append( aInput.substring(startIdx) );
     return result.toString();
  }

} 

